<template>
	<div ref="chartRef" class="echartsClass"></div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const props = defineProps<{
	data: []
}>()

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
	if (!chartRef.value) {
		return
	}
	chartInstance?.dispose()
	chartInstance = echarts.init(chartRef.value)
	updateChart()
	window.addEventListener('resize', handleChartResize)
}

const chartData = {
	legendData: [
		'未宣贯',
		'累计宣贯人数 < 100 人或宣贯 1 次',
		'100 人 ≤ 累计宣贯人数 < 500 人或宣贯 1 - 2 场',
		'累计宣贯人数 ≥ 500 人或宣贯 3 场及以上'
	],
	seriesData: [
		{ value: 30, name: '未宣贯' }, // 示例数据，需替换为真实数据
		{ value: 10, name: '累计宣贯人数 < 100 人或宣贯 1 次' },
		{ value: 30, name: '100 人 ≤ 累计宣贯人数 < 500 人或宣贯 1 - 2 场' },
		{ value: 30, name: '累计宣贯人数 ≥ 500 人或宣贯 3 场及以上' }
	]
}

const updateChart = () => {
	if (!chartInstance) {
		return
	}
	const option = {
		title: {
			text: '标准宣贯'
		},
		tooltip: {
			trigger: 'item'
		},
		legend: {
			orient: 'vertical',
			left: 'right',
			data: chartData.legendData
		},
		series: [
			{
				name: '标准宣贯',
				type: 'pie',
				radius: ['0%', '70%'],
				avoidLabelOverlap: false,
				label: {
					show: true,
					position: 'outside',
					formatter: '{c}'
				},
				emphasis: {
					label: {
						show: true,
						fontSize: '16',
						fontWeight: 'bold'
					}
				},
				labelLine: {
					show: true
				},
				data: chartData.seriesData
			}
		]
	}

	chartInstance.setOption(option)
}

const handleChartResize = () => {
	chartInstance?.resize()
}

const cleanupChart = () => {
	window.removeEventListener('resize', handleChartResize)
	chartInstance?.dispose()
}

onBeforeUnmount(() => {
	cleanupChart()
})

onMounted(() => {
	initChart()
})
</script>
<style lang="scss" scoped>
.echartsClass {
	width: 550px;
	height: 400px;
}
</style>
